﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.IO;
using System.Security.AccessControl;
using LiveWebServiceBase;
using LiveWebServiceBase.ServiceUserSettings;
using LiveWebServiceBase.Security;

namespace LiveWebServiceAdmin.ActionPages
{
    public partial class manageusers : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {
            if (!string.IsNullOrEmpty(Page.Request.QueryString["edituser"]))
            {
                tbNewLogin.Text = Page.Request.QueryString["edituser"];

                ilbPass1.Text = "New password:";
                ilbPass2.Text = "Repeat new password:";
                btnCreateUser.Text = "Save";

                RequiredFieldValidator2.Enabled = false;
                RequiredFieldValidator3.Enabled = false;
            }
        }

        protected void btnCreateUser_Click(object sender, EventArgs e)
        {
            try
            {
                string username = string.Empty;
                string domain = string.Empty;
                string password = string.Empty;

                if (Session["userData"] != null)
                {
                    string[] tmp = Authorization.DecryptString(Session["userData"].ToString()).Split(';');

                    username = tmp[0];
                    domain = (string.IsNullOrEmpty(tmp[1])) ? Environment.MachineName : tmp[1];
                    password = tmp[2];
                }
                else
                    throw new MemberAccessException("Error on impersonation.");
                
                Impersonator ipm = new Impersonator(username, domain, password);

                try
                {
                    if (tbPass1.Text == tbPass2.Text)
                    {
                        if (!string.IsNullOrEmpty(Page.Request.QueryString["edituser"]))
                        {
                            string oldUserName = Page.Request.QueryString["edituser"];
                            string newUserName = tbNewLogin.Text;
                            string newUserPassword = tbPass1.Text;

                            DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
                            DirectoryEntry OldUser = AD.Children.Find(oldUserName, "user");

                            if (oldUserName.ToLower() != newUserName)
                            {
                                OldUser.Rename(newUserName);

                                UserSettings usItem = new UserSettings(oldUserName);
                                usItem.ReanmeUser(newUserName);

                                DirectoryInfo dirinfo = new DirectoryInfo(Settings.Paths.PathToConfigDir + "\\" + oldUserName);

                                DirectorySecurity myDirectorySecurity = dirinfo.GetAccessControl();
                                myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(newUserName, FileSystemRights.FullControl,
                                    InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
                                dirinfo.SetAccessControl(myDirectorySecurity);

                                dirinfo.MoveTo(Settings.Paths.PathToConfigDir + "\\" + newUserName);
                            }

                            if (!string.IsNullOrEmpty(tbPass1.Text))
                                OldUser.Invoke("SetPassword", newUserPassword);

                            OldUser.CommitChanges();
                        }
                        else
                        {
                            string UserName = tbNewLogin.Text;
                            string UserPassword = tbPass1.Text;

                            DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
                            DirectoryEntry NewUser = AD.Children.Add(UserName, "user");
                            NewUser.Invoke("SetPassword", new object[] { UserPassword });
                            NewUser.Invoke("Put", new object[] { "Description", "Live WebService User" });
                            NewUser.CommitChanges();
                            DirectoryEntry grp;

                            grp = AD.Children.Find(Settings.UserInfo.userGroupName, "group");
                            if (grp != null)
                            {
                                grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
                            }
                            else
                            {
                                lblErrorTextNewUser.Text = "Local group " + Settings.UserInfo.userGroupName + " doesn't exist.";
                            }

                            DirectoryInfo dirinfo = new DirectoryInfo(Settings.Paths.PathToConfigDir);

                            DirectorySecurity myDirectorySecurity = dirinfo.GetAccessControl();
                            myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(UserName, FileSystemRights.FullControl,
                                InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
                            dirinfo.SetAccessControl(myDirectorySecurity);

                            dirinfo.CreateSubdirectory(UserName);
                        }

                        IsCompleted.Value = "true";
                    }
                }
                finally
                {
                    ipm.Dispose();
                }
            }
            catch (Exception ex)
            {
                lblErrorTextNewUser.Text = ex.Message;
            }
        }
    }
}
